#include <mymuduo/tcp_server.h>
#include <mymuduo/logger.h>

#include <string>
#include <functional>
#include <future>

class EchoServer {
    public:
    EchoServer(EventLoop *loop,const InetAddress &addr,const std::string &name):loop_(loop),server_(loop,addr,name) {
        //注册回调函数
        server_.set_connection_callback(
            std::bind(&EchoServer::on_connection,this,std::placeholders::_1));
        server_.set_message_callback(
            std::bind(&EchoServer::on_message,this,std::placeholders::_1,std::placeholders::_2,std::placeholders::_3));
        server_.set_thread_init_callback(std::bind(&EchoServer::on_thread_init_callback,this,std::placeholders::_1));
        server_.set_write_complete_callback(std::bind(&EchoServer::on_write_complete_callback,this,std::placeholders::_1));
        //设置合适的loop线程数量，loop_thread
        server_.set_thread_num(3);
    }

    void start() {
        server_.start();
    }
private:
    //连接建立或者断开的回调
    void on_connection(const TcpConnectionPtr &conn) {
        if (conn->connected()) {
            LOG_INFO("Connection UP : %s",conn->peer_address_().to_ip_port().c_str());
        }else {
            LOG_INFO("Connection DOWN : %s",conn->peer_address_().to_ip_port().c_str());
        }
    }

    //可读写事件回调
    void on_message(const TcpConnectionPtr &conn,Buffer *buf,Timestamp time) {
        std::string msg = buf->retrieve_all_as_string();
        LOG_INFO("Received from %s at %s: %s (size: %zu bytes)",
                 conn->peer_address_().to_ip_port().c_str(),
                 time.to_string().c_str(),
                 msg.c_str(),
                 msg.size());
        conn->send(msg);
        if (msg == "quit\r\n") {
            LOG_INFO("Received quit command, closing connection with %s",
                conn->peer_address_().to_ip_port().c_str());
            // 关闭连接（主动发起关闭）
            conn->shutdown(); // 或 conn->close();
        }
    }

    // 线程初始化回调函数：为新线程设置名称并打印日志
    void on_thread_init_callback(EventLoop* loop) {
        // 1. 设置线程名称（格式：SubLoop-线程ID，便于调试）
        std::string thread_name = "SubLoop-" + std::to_string(current_thread::tid());
        // pthread_setname_np 限制名称长度（通常≤15字符），截断处理
        if (thread_name.size() > 15) {
            thread_name = thread_name.substr(0, 15);
        }
        pthread_setname_np(pthread_self(), thread_name.c_str());

        // 2. 记录线程启动日志（包含线程ID和EventLoop地址）
        LOG_INFO("ThreadInitCallback: SubLoop %p started in thread %d (name: %s)",
                 loop, current_thread::tid(), thread_name.c_str());

        // 3. 可选：为该EventLoop注册一个周期性定时器（示例）
        // 比如每10秒打印一次线程存活日志
        // loop->run_every(10.0, [loop]() {
        //     LOG_DEBUG("SubLoop %p in thread %d is running",
        //               loop, current_thread::tid());
        // });

        // 4. 可选：初始化线程局部变量（如线程专属的内存池、统计器等）
        // current_thread::set_local_data(...);
    }

    void on_write_complete_callback(const TcpConnectionPtr& conn) {
        LOG_INFO( "Connection - Write complete, connection: " ,conn->name().c_str());
    }


    EventLoop *loop_;
    TcpServer server_;

};

int main() {
    EventLoop loop;
    InetAddress addr(8000);
    EchoServer server(&loop,addr,"EchoServer-01");//Acceptor non-blocking listenfd create bind
    server.start();//listen loopthread listenfd=>accept_channel=>main_loop=>
    loop.loop();//启动main_loop的底层Poller

    return 0;
}































